<?php
require_once '_utils/database.php';
require_once '_utils/get_info.php';

function choose($array, $number) {
	$choices = array();

	if ($number < 1) return array(array());

	foreach ($array as $i => $x) {
		$array2 = $array;
		unset($array2[$i]);
		$a = $array[$i];
		$b = choose($array2, $number-1);
		foreach ($b as $j => $y) {
			array_unshift($b[$j], $a);
		}
		$choices = array_merge($choices, $b);
	}

	return $choices;
}

function findPeople($name) {
	open_db();

	$name = mysql_real_escape_string($name);
	$names = split('[, ]', $name);
	foreach($names as $i => $n) {
		$names[$i] = trim($n);
		if ($names[$i] == '')
			unset($names[$i]);
	}

	$names = choose($names, count($names));

	$names2 = array();
	foreach ($names as $a)
		$names2[] = '%'.implode('%', $a).'%';
	$where = "name like '".implode("' or name like '", $names2)."'"; 


	$names = array();
	$people = mysql_query("select person_id, name from persons where $where");
	while ($person = mysql_fetch_array($people))
		$names[] = array('person_id' =>$person['person_id'], 'name' => $person['name']) ;

	return $names;
}

$people = empty($_GET['name']) ? array() : findPeople(htmlspecialchars($_GET['name']));
if (count($people) == 1) {
	header("Location: " . getBasePath() . "/person/".$people[0]["person_id"]);
	exit(0);
}

include "header.php";

echo "<div id='search_results'>";
if (!empty($_GET['name'])) {
	$name = htmlspecialchars($_GET['name']);
	echo "<div id='search_title_box'><span id='search_title_text'>Search Results for <strong>$name</strong>:</span></div>";

	$people = findPeople($name);

	if (count($people) == 1)
		header("Location: " . getBasePath() . "/person/".$people[0]["person_id"]);
	else if (count($people) == 0)
		echo getEmptySearchResultText($name);
	else
		foreach ($people as $person)
			echo "<a href='" . getBasePath() . "/person/" . $person["person_id"] . "'>$person[name]</a><br/>";
}
echo "</div>";

include "footer.php";
?>
